package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.NumberConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 菜品管理业务层
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private  SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 统计分类
     * @param id
     * @return
     */
    @Override
    public Integer tallyOfDish(Long id) {
        Integer tally = dishMapper.countByCategoryId(id);
        return tally;
    }

    /**
     * 菜品分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult queryPage(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.queryPage(dto);
        log.info(page.getResult().toString());
        return new PageResult(page.getTotal(), page.getResult());

    }

    /**
     * 根据id批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //起售的菜品不能删除！
        List<Dish> dishes = dishMapper.queryStatus(ids);
        for (Dish dish : dishes) {
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

        }
        //TODO 无套餐信息可能需要优化
        //被套餐关联的菜品不能删除
        List<Long> setmeals = setmealDishMapper.getByDishIds(ids);
        if (!setmeals.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //可批量删除菜品！
        dishMapper.deleteByids(ids);
        //批量删除口味
        dishFlavorMapper.deleteByDishIds(ids);
        //清楚redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 保存菜品
     *
     * @param dto
     */
    @Override
    @Transactional
    public void saveBatch(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.saveBatch(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dto.getFlavors();
        if (!flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.save(flavors);//最好包进去
        }
        //清楚redis缓存
        Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
    }

    /**
     * 更新菜品
     *
     * @param dto
     */
    @Override
    @Transactional
    public void updateBatch(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.update(dish);
        List<Long> dishIds = Collections.singletonList(dish.getId());
        dishFlavorMapper.deleteByDishIds(dishIds);
        List<DishFlavor> flavors = dto.getFlavors();
        Long dishId = dish.getId();
        if (!flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.save(flavors);//最好包进去
        }
        //清楚redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据id查询
     * 下次不要写DishVo了，应该写Dish对象
     * @param id
     * @return
     */
    @Override
    public DishVO queryById(Long id) {
        DishVO dishVo = dishMapper.queryById(id);
        List<DishFlavor> flavors = dishFlavorMapper.queryByDishId(id);
        dishVo.setFlavors(flavors);
        return dishVo;
    }

    /**
     * 菜品启用禁用
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder().status(status).id(id).build();
        dishMapper.update(dish);
        //停售相关套餐
       List<Long> setmealIds= setmealDishMapper.queryByDishId(id);
        if (status.equals(StatusConstant.DISABLE)) {
            if (!setmealIds.isEmpty()) {
                setmealIds.forEach(setmealId ->{
                    Setmeal setmeal = Setmeal.builder().id(setmealId).status(status).build();
                    setmealMapper.update(setmeal);
                });
            }
        }
        //清楚redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> queryByCategoryId(Long categoryId) {
        List<DishVO> dishVOList = dishMapper.queryByCategoryId(categoryId);
        return dishVOList;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.queryByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
